/**
 *
 */
package com.wedroid.r2d2.message.parser;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.demo2do.core.utils.JsonUtils;
import com.wedroid.entity.message.Location;
import com.wedroid.entity.message.MessageType;
import com.wedroid.r2d2.message.RawMessage;
import com.wedroid.r2d2.resource.ResourceManager;

/**
 * @author lute
 */
@Component("textContentParser")
public class TextContentParser implements ContentParser {

    private final String locationRegex = "/cgi-bin/mmwebwx-bin/webwxgetpubliclinkimg\\?url=xxx&msgid=\\d*&pictype=location";

    private final Pattern locationPattern = Pattern.compile(locationRegex);

    @Autowired
    private ResourceManager resourceManager;

    /* (non-Javadoc)
     * @see com.wedroid.r2d2.message.parser.ContentParser#supportsMessageType(com.wedroid.entity.message.MessageType)
     */
    public boolean supportsMessageType(MessageType messageType) {
        return MessageType.TEXT.equals(messageType);
    }

    /* (non-Javadoc)
     * @see com.wedroid.r2d2.message.parser.ContentParser#parse(com.wedroid.r2d2.message.RawMessage, java.lang.String)
     */
    public String parse(RawMessage rawMessage, String escapedContent) {
        if (isLocationMessage(escapedContent)) {
            Location location = Location.contentOf(escapedContent);
            if (location != null) {
                // Download map image
                String fromUserName = rawMessage.getFromUserName();
                String mapUrl = resourceManager.downloadPublicLinkImg(rawMessage.getMsgId(), fromUserName, location.getMapUrl());
                if (StringUtils.isNotBlank(mapUrl)) {
                    location.mapUrl(mapUrl);
                }

                location.url(rawMessage.getUrl());
                return JsonUtils.toJsonString(location);
            }
        }

        return escapedContent;
    }

    /**
     * @param escapedContent
     * @return
     */
    private boolean isLocationMessage(String escapedContent) {
        Matcher matcher = locationPattern.matcher(escapedContent);
        return matcher.find();
    }

}
